require("sdk/libs/strophe");
let WebIM = require("utils/WebIM")["default"];
let msgStorage = require("comps/chat/msgstorage");
let msgType = require("comps/chat/msgtype");
let disp = require("utils/broadcast");
let { produce } = require("utils/immer");
var onfire = require('utils/event')


wx.clientReceiptt = function (data) {
  console.log("已读回执")
  onfire.fire('clientReceiptt');

};
wx.serverReceiptt = function (data) {
  //onfire.un('serverReceiptt');
  console.log("服务器已发送")
  onfire.fire('serverReceiptt');

};
let chatIm = {
  grant_type: "password",
  CHAT_STATUS_SEND: 0,
  CHAT_STATUS_RECEIVED: 1,
  CHAT_STATUS_DILEVERD: 2,
  CHAT_STATUS_READED: 3,
};

function getCurrentRoute() {
  let pages = getCurrentPages();
  let currentPage = pages[pages.length - 1];
  return currentPage.route;
}
// 定义socket连接对象
chatIm.conn = {
  closed: false,
  curOpenOpt: {},
  loginOpen(user) {
      var uid = user.user;
    var pwd = user.pwd;
      console.log(111,user)
    // 保存自己的用户名key
      wx.setStorageSync("myUsername", uid);
    //存储到变量
      chatIm.uid = uid;
    // chat登录
    chatIm.conn.open({
      apiUrl: WebIM.config.apiURL,
        user: uid,
      pwd: pwd,
      grant_type: this.grant_type,
      appKey: WebIM.config.appkey
    });
  },
  open(opt) {
    this.curOpenOpt = opt;
    WebIM.conn.open(opt);
    this.closed = false;
  },
  reopen() {
    if (this.closed) {
      this.open(this.curOpenOpt);
    }
  }
};

// 错误处理
chatIm.onMessageError = function (err) {
  if (err.type === "error") {
    wx.showToast({
      title: err.errorText
    });
    return false;
  }
  return true;
};
// 消息回执
chatIm.ack = function (receiveMsg) {
  // 需要发送已读回执的消息id
  var bodyId = receiveMsg.id;
  var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
  ackMsg.set({
    id: bodyId,
    to: receiveMsg.from
  });
  WebIM.conn.send(ackMsg.body);
};
// 消息统计数据及提示的自动计算
chatIm.calcUnReadSpot = function () {
  let myName = wx.getStorageSync("myUsername");
  let members = wx.getStorageSync("member") || [];
  let count = members.reduce(function (result, curMember, idx) {
    let chatMsgs = wx.getStorageSync(curMember.name + "-" + myName) || [];
    return result + chatMsgs.length;
  }, 0);
  console.log(1111,getApp().globalData.unReadSpot)
  getApp().globalData.unReadSpot = count > 0;
  console.log("disp fire em.xmpp.unreadspot:" + count);
  disp.fire("em.xmpp.unreadspot", count);
}

// 加载时进行相关初始化
chatIm.onLaunch = function () {
  // 调用 API 从本地缓存中获取数据
  var me = this;
  disp.on("em.main.ready", function () {
    me.calcUnReadSpot();
  });
  disp.on("em.chatroom.leave", function () {
    me.calcUnReadSpot();
  });
  disp.on("em.chat.session.remove", function () {
    me.calcUnReadSpot();
  });
  

  // 定义im事件
  WebIM.conn.listen({
    onOpened(message) {
      console.log("onOpened", message);
      console.log(111, getCurrentRoute())
      WebIM.conn.setPresence();
      if (getCurrentRoute() == "pages/login/login") {
        console.log(me)
        me.onLoginSuccess(wx.getStorageSync("myUsername"));
      }

    },
   
    onClosed() {
      me.conn.closed = true;
    },
    
    onPresence(message) {
      console.log("onPresence", message);
      switch (message.type) {
        case "unsubscribe":
          // pages[0].moveFriend(message);
          break;
        case "subscribed":
          wx.showToast({
            title: "添加成功",
            duration: 1000
          });
          break;
        default:
          break;
      }
    },
    onAudioMessage(message) {
      console.log("onAudioMessage", message);
      if (message) {
        if (me.onMessageError(message)) {
          msgStorage.saveReceiveMsg(message, msgType.AUDIO);
        }
        me.calcUnReadSpot();
        ack(message);
      }
    },
    onTextMessage(message) {
      console.log("onTextMessage", message);
      if (message) {
        if (me.onMessageError(message)) {
          msgStorage.saveReceiveMsg(message, msgType.TEXT);
        }
        me.calcUnReadSpot();
        me.ack(message);
      }
    },
    onEmojiMessage(message) {
      console.log("onEmojiMessage", message);
      if (message) {
        if (me.onMessageError(message)) {
          msgStorage.saveReceiveMsg(message, msgType.EMOJI);
        }
        me.calcUnReadSpot();
        me.ack(message);
      }
    },
    onPictureMessage(message) {
      console.log("onPictureMessage", message);
      if (message) {
        if (me.onMessageError(message)) {
          msgStorage.saveReceiveMsg(message, msgType.IMAGE);
        }
        me.calcUnReadSpot();
        me.ack(message);
      }
    },
    //收到消息送达服务器回执
    onReceivedMessage: function (message) {
      wx.serverReceiptt(message)
    },
    //收到消息送达客户端回执
    onDeliveredMessage: function (message) {
      //console.log("客户端回执" + message)
      //wx.setChat(message)
    },
    //收到消息已读回执
    onReadMessage: function (message) {
      //console.log("已读回执" + message)
      wx.clientReceiptt(message)
    },     
    // 各种异常
    onError(error) {
      // 16: server-side close the websocket connection
      if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
        if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
          return;
        }
        wx.showToast({
          title: "server-side close the websocket connection",
          duration: 1000
        });
        wx.redirectTo({
          url: "../login/login"
        });
        return;
      }
      // 8: offline by multi login
      if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
        wx.showToast({
          title: "offline by multi login",
          duration: 1000
        });
        wx.redirectTo({
          url: "../login/login"
        });
      }
      if (error.type == WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
        wx.showModal({
          title: "用户名或密码错误",
          confirmText: "OK",
          showCancel: false
        });
      }
    },
  });
},
  chatIm.onLoginSuccess=function (myName) {
    wx.showToast({
      title: "登录成功",
      icon: "success",
      duration: 1000
    });
    setTimeout(function () {
      wx.redirectTo({
        url: "../main/main?myName=" + myName
      });
    }, 1000);
  },


// 取得所有未读消息数量
chatIm.getTotalUnreadCnt = function () {
  var member = wx.getStorageSync("member");
  var myName = wx.getStorageSync("myUsername");
  let cnt = 0;
  for (let i = 0; i < member.length; i++) {
    let newChatMsgs = wx.getStorageSync(member[i].name + myName) || [];
    if (!newChatMsgs) {
      continue;
    }
    cnt = cnt + newChatMsgs.length;
  }
  return cnt;
}

module.exports = chatIm;






